package design.simdi.code.final_paper.site.panels.licente.proiecte;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.Page;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.authorization.strategies.role.Roles;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

import design.simdi.code.final_paper.core.entities.Person;
import design.simdi.code.final_paper.core.entities.Project;
import design.simdi.code.final_paper.core.entities.StudentCandidat;
import design.simdi.code.final_paper.core.entities.User;
import design.simdi.code.final_paper.core.services.ApplicationService;
import design.simdi.code.final_paper.core.services.ServiceException;
import design.simdi.code.final_paper.core.services.UserService;
import design.simdi.code.final_paper.site.application.ApplicationRoles;
import design.simdi.code.final_paper.site.application.MyAuthenticatedWebSession;
import design.simdi.code.final_paper.site.pages.BasePage;
import design.simdi.code.final_paper.utils.ActionToolbar;
import design.simdi.code.final_paper.utils.MyDataTable;
import design.simdi.code.final_paper.utils.StatusStudentCandidat;
import design.simdi.code.final_paper.utils.ToolbarItem;
import design.simdi.code.final_paper.utils.YesNoModalWindow;

/**
 * 
 * @author Marius Dumitriu - (Jun 19, 2010 - 9:11:14 PM)
 * 
 */
public class ProjectsActionToolbar extends ActionToolbar {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@SpringBean
	private ApplicationService applicationService;
	@SpringBean
	private UserService userService;

	private YesNoModalWindow deleteYesNoConfirmationModal;

	public ProjectsActionToolbar(MyDataTable<?> table) {
		super(table);
		deleteYesNoConfirmationModal = new YesNoModalWindow("delete.confirmation", "confirmare2") {

			private static final long serialVersionUID = 1L;

			@Override
			public void onYes(AjaxRequestTarget target) {
				Project k = (Project) getTable().getSelectedRow().getModelObject();
				applicationService.removeProject(k);

			}

			@Override
			public void onNo(AjaxRequestTarget target) {

			}
		};

		deleteYesNoConfirmationModal.setOutputMarkupPlaceholderTag(true);

		add(deleteYesNoConfirmationModal);
		setOutputMarkupId(true);

	}

	@Override
	public List<ToolbarItem> getItemsList() {
		List<ToolbarItem> lista = new ArrayList<ToolbarItem>();
		Roles roluriCurente = MyAuthenticatedWebSession.get().getRoles();
		if (MyAuthenticatedWebSession.get().isSignedIn() && roluriCurente.contains(ApplicationRoles.PROFESSOR)) {
			lista.add(ToolbarItem.ADD);
			lista.add(ToolbarItem.ADD_FROM_IDEA);
		}
		lista.add(ToolbarItem.VIEW);
		if (MyAuthenticatedWebSession.get().isSignedIn() && roluriCurente.contains(ApplicationRoles.PROFESSOR)) {
			lista.add(ToolbarItem.MODIFY);
			lista.add(ToolbarItem.DELETE);
		}

		if (MyAuthenticatedWebSession.get().isSignedIn()
				&& (roluriCurente.contains(ApplicationRoles.STUDENT) || roluriCurente
						.contains(ApplicationRoles.ABSOLVENT))) {
			lista.add(ToolbarItem.CANDIDATE);
			lista.add(ToolbarItem.CANDIDATE_NO);
		}
		return lista;

	}

	@Override
	public void onAction(ToolbarItem toolbarItem, AjaxRequestTarget target) {
		switch (toolbarItem) {
		case ADD:
			onAddAction(target);
			break;

		case DELETE:
			onDeleteAction(target);
			break;
		case MODIFY:
			onModifyAction(target);
			break;
		case VIEW:
			onViewAction(target);
			break;
		case CANDIDATE:
			onCandidateAction(target);
			break;
		case CANDIDATE_NO:
			onCandidateNoAction(target);
			break;
		case ADD_FROM_IDEA:
			onAddFromIdeaAction(target);
			break;
		}
	}

	private void onAddFromIdeaAction(AjaxRequestTarget target) {
		AddProjectFromIdeaWizardPanel addWizardPanel = new AddProjectFromIdeaWizardPanel("panel", null);
		addWizardPanel.setOutputMarkupId(true);
		Page page = this.getPage();

		page.get("content:tabs:panel").replaceWith(addWizardPanel);

		target.addComponent(page.get("content"));
	}

	private void onCandidateNoAction(AjaxRequestTarget target) {
		try {
			if (getTable().getSelectedRow() == null)
				throw new ServiceException("table.row.not.selected");

			User currentUser = ((MyAuthenticatedWebSession) getSession()).getCurrentUser();

			Person pers = userService.findPersonByUser(currentUser);

			Project d = (Project) getTable().getSelectedRow().getModelObject();
			StudentCandidat sc = applicationService.findStudentCandidatByProject(d, pers);
			if (sc == null)
				throw new ServiceException("project.candidate.no");

			if (sc.getStatus().equals(StatusStudentCandidat.ACCEPTAT))
				throw new Exception("project.candidate.remove.decision.taken");

			applicationService.removeStudentCandidat(sc);

			Page page = this.getPage();
			target.addComponent(page.get("content:tabs:panel:table-container"));

			target.addComponent(page.get(BasePage.ERRORS_PANEL));
			info(page.getString("operation.success"));

		} catch (ServiceException e) {
			warn(getString(e.getMessage()));

		} catch (Exception e) {
			error(getString(e.getMessage()));

		}

	}

	private void onCandidateAction(AjaxRequestTarget target) {
		try {
			if (getTable().getSelectedRow() == null)
				throw new ServiceException("table.row.not.selected");
			Project d = (Project) getTable().getSelectedRow().getModelObject();
			User currentUser = ((MyAuthenticatedWebSession) getSession()).getCurrentUser();

			Person pers = userService.findPersonByUser(currentUser);

			if (applicationService.findStudentCandidatByProject(d, pers) != null)
				throw new ServiceException("project.candidate.duplicate");

			if (d.isAvailable() == false)
				throw new ServiceException("project.not.available");

			StudentCandidat sc = new StudentCandidat();
			sc.setProject(d);
			if (pers.getStudent() != null)
				sc.setStudent(pers.getStudent());
			else
				sc.setAbsolvent(pers.getAbsolvent());
			sc.setStatus(StatusStudentCandidat.CANDIDAT);

			applicationService.saveStudentCandidat(sc);
			target.addComponent(this.getPage().get("content:tabs:panel:table-container"));
			target.addComponent(this.getPage().get(BasePage.ERRORS_PANEL));
			info(getString("operation.success"));

		} catch (ServiceException e) {
			warn(getString(e.getMessage()));

		}

	}

	private void onViewAction(AjaxRequestTarget target) {
		try {
			if (getTable().getSelectedRow() == null)
				throw new ServiceException("table.row.not.selected");

			ViewProjectDetails detailsPanel = new ViewProjectDetails("panel", new Model<Project>((Project) getTable()
					.getSelectedRow().getModelObject()));
			detailsPanel.setOutputMarkupId(true);
			Page page = this.getPage();

			page.get("content:tabs:panel").replaceWith(detailsPanel);

			target.addComponent(page.get("content"));

		} catch (ServiceException e) {
			warn(getString(e.getMessage()));

		}

	}

	private void onModifyAction(AjaxRequestTarget target) {
		try {
			if (getTable().getSelectedRow() == null)
				throw new ServiceException("table.row.not.selected");
			AddProjectWizardPanel addWizardPanel = new AddProjectWizardPanel("panel", (Project) getTable()
					.getSelectedRow().getModelObject());
			addWizardPanel.setOutputMarkupId(true);
			Page page = this.getPage();

			page.get("content:tabs:panel").replaceWith(addWizardPanel);

			target.addComponent(page.get("content"));

		} catch (ServiceException e) {
			warn(getString(e.getMessage()));

		}

	}

	private void onDeleteAction(AjaxRequestTarget target) {

		try {
			if (getTable().getSelectedRow() == null)
				throw new ServiceException("table.row.not.selected");

			Project p = (Project) getTable().getSelectedRow().getModelObject();

			if (getApplicationService().findStudentCandidatByProject(p, getCurrentPerson()) != null)
				throw new ServiceException("candidati.asociati");

			if (getApplicationService().findStudentAdmisByProject(p, getCurrentPerson()) != null)
				throw new ServiceException("admisi.asociati");

			deleteYesNoConfirmationModal.show(target);

		} catch (ServiceException e) {
			warn(getString(e.getMessage()));

		}

	}

	private void onAddAction(AjaxRequestTarget target) {
		AddProjectWizardPanel addWizardPanel = new AddProjectWizardPanel("panel", null);
		addWizardPanel.setOutputMarkupId(true);
		Page page = this.getPage();

		page.get("content:tabs:panel").replaceWith(addWizardPanel);

		target.addComponent(page.get("content"));

	}

	@Override
	public String getToolbarName(ToolbarItem toolbarItem) {
		return getString(toolbarItem.getName());
	}

	public void setApplicationService(ApplicationService applicationService) {
		this.applicationService = applicationService;
	}

	public ApplicationService getApplicationService() {
		return applicationService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserService getUserService() {
		return userService;
	}

}
